package com.huangkailong.sqlprinter.agent.mysql.driver;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;

import java.util.Objects;

/**
 * 5.1.44 之前的的驱动
 *
 * @author huangkailong
 * @since 1.0.0
 */
public class OldDriverAgent extends DriverAgent{
    private static final String CLASS_NAME_PREPARED_STATEMENT = "com.mysql.jdbc.PreparedStatement";
    private static final String METHOD_NAME_FILL_SEND_PACKET = "fillSendPacket";
    public static final String CLASS_NAME_BYTE_ARRAY_ARRAY = "byte[][]";
    public static final String CLASS_NAME_INPUT_STREAM_ARRAY = "java.io.InputStream[]";
    public static final String CLASS_NAME_BOOL_ARRAY = "boolean[]";
    public static final String CLASS_NAME_INT_ARRAY = "int[]";

    public OldDriverAgent() {
        super();
    }

    @Override
    public CtClass enhanceClass() throws Exception {
        final ClassPool classPool = ClassPool.getDefault();
        final CtClass preparedStatementCtClass = classPool.get(CLASS_NAME_PREPARED_STATEMENT);
        final CtMethod fillSendPacketCtMethod = preparedStatementCtClass.getDeclaredMethod(METHOD_NAME_FILL_SEND_PACKET,
                classPool.get(new String[]{CLASS_NAME_BYTE_ARRAY_ARRAY, CLASS_NAME_INPUT_STREAM_ARRAY, CLASS_NAME_BOOL_ARRAY, CLASS_NAME_INT_ARRAY}));
        if(Objects.nonNull(fillSendPacketCtMethod)){
            fillSendPacketCtMethod.insertBefore(getSqlSrc("sql"));
        }
        return preparedStatementCtClass;
    }

    @Override
    public boolean doIsSupport(String className) {
        return className.equals(CLASS_NAME_PREPARED_STATEMENT);
    }

    @Override
    protected String generateSqlGetSrc() {
        return "String sql = asSql();";
    }
}
